﻿using System;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.PubSubEvents;
using Mitosoft.Definitions.Events;
using Prism.Common.Interfaces;

namespace Prism.Common.Services
{
  /// <summary>
  /// Service used to manage overall application tasks like shutdown.
  /// </summary>
  public class ApplicationManagerService : IApplicationManagerService
  {
    #region fields

    /// <summary>
    /// Represents <see cref="ShutDownApplicationCommand"/>
    /// </summary>
    protected CompositeCommand _shutDownApplicationCommand;

    /// <summary>
    /// Represents <see cref="ApplicationIsShuttingDown"/>
    /// </summary>
    protected bool _applicationIsShuttingDown;

    /// <summary>
    /// Represents <see cref="ZoomFactor"/>
    /// </summary>
    protected double _zoomFactor = 1.0;

    /// <summary>
    /// Represents the event aggregator.
    /// </summary>
    protected IEventAggregator _eventAggregator;

    #endregion

    #region constructors

    /// <summary>
    /// Creates a new <see cref="ApplicationManagerService"/> instance.
    /// </summary>
    // ReSharper disable once EmptyConstructor
    public ApplicationManagerService(IEventAggregator eventAggregator)
    {
      _eventAggregator = eventAggregator;
    }

    #endregion

    #region properties

    /// <summary>
    /// Gets or sets the zoom factor.
    /// </summary>
    public double ZoomFactor
    {
      get { return _zoomFactor; }
      set
      {
        if (Math.Abs(value - _zoomFactor) < 0.001)
          return;
        
        _zoomFactor = value;

        _eventAggregator.GetEvent<ApplicationZoomFactorChangedEvent>().Publish(_zoomFactor);
      }
    }

    /// <summary>
    /// Gets or sets whether the application is currently shutting down.
    /// </summary>
    public bool ApplicationIsShuttingDown 
    { 
      get { return _applicationIsShuttingDown; } 
      set { _applicationIsShuttingDown = value; } 
    }

    /// <summary>
    /// Application command used to shut down the application.
    /// </summary>
    public CompositeCommand ShutDownApplicationCommand
    {
      get
      {
        return 
          _shutDownApplicationCommand ?? 
            (_shutDownApplicationCommand = 
              new CompositeCommand(
                  monitorCommandActivity: false));
      }
    }

    #endregion

    #region methods
    #endregion
  }
}
